package com.xmut.mall.member.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.xmut.mall.member.constant.MemberCouponStatusEnum;
import com.xmut.mall.member.entity.MemberCartEntity;
import com.xmut.mall.member.feign.CouponFeignService;
import com.xmut.mall.member.searchparam.UserCentCouponSearchParam;
import com.xmut.mall.member.utils.PageUtil;
import com.xmut.mall.member.utils.RespBean;
import com.xmut.mall.member.vo.CouponEntityVo;
import com.xmut.mall.member.vo.PageVO;
import com.xmut.mall.member.vo.UserCenterPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.member.utils.PageUtils;
import com.xmut.mall.member.utils.Query;

import com.xmut.mall.member.dao.MemberCouponDao;
import com.xmut.mall.member.entity.MemberCouponEntity;
import com.xmut.mall.member.service.MemberCouponService;


@Service("memberCouponService")
public class MemberCouponServiceImpl extends ServiceImpl<MemberCouponDao, MemberCouponEntity> implements MemberCouponService {

    @Autowired
    private CouponFeignService couponFeignService;

    /**
     * 用户领取优惠券
     *
     * @param params
     * @return
     */
    @Override
    public RespBean userReceiveCoupon(Map<String, Object> params) {
        Long userId = MapUtil.getLong(params, "userId");
        Long couponId = MapUtil.getLong(params, "couponId");

        // 远程查询优惠券信息
        RespBean couponFeignResp = couponFeignService.getCoupon(couponId);
        CouponEntityVo couponEntity = JSON.parseObject(JSON.toJSONString(couponFeignResp.getObj()), CouponEntityVo.class);
        if (couponEntity.getPublishNum() < couponEntity.getReceivedNum()) {
            return RespBean.error("该优惠券已经领完了");
        }
        // 查询用户领取本优惠券几次了
        Integer userReceiveCount = this.count(new QueryWrapper<MemberCouponEntity>()
                .eq("coupon_id", couponId)
                .eq("member_id", userId));
        if (couponEntity.getCouponLimitNum() <= userReceiveCount) {
            return RespBean.error("超过当前优惠券领取上限");
        }

        // 进行领取
        MemberCouponEntity entity = new MemberCouponEntity();
        entity.setStartTime(couponEntity.getStartTime());
        entity.setEndTime(couponEntity.getEndTime());
        entity.setConsumeThreshold(couponEntity.getConsumeThreshold());
//        entity.setConsumptionTime();
        entity.setCouponId(couponId);
        entity.setCouponType(couponEntity.getCouponType());
        entity.setDiscount(couponEntity.getCouponDiscount());
        entity.setGetType(couponEntity.getGetType());
        // 判断是否是平台券
        if (couponEntity.getStoreId().equals(0L)) {
            entity.setPlatformFlag(true);
        } else {
            entity.setPlatformFlag(false);
        }
        entity.setMemberId(userId);
        entity.setPrice(couponEntity.getPrice());
        entity.setScopeId(couponEntity.getScopeId());
        entity.setScopeType(couponEntity.getScopeType());
        entity.setStoreCommission(couponEntity.getStoreCommission());
        entity.setStoreId(couponEntity.getStoreId());
        entity.setStoreName(couponEntity.getStoreName());
        entity.setCreateTime(new Date());
        boolean save = this.save(entity);
        if (save) {
            // 给coupon减库存
            params.put("num", 1);// 因为这里就领了一个
            couponFeignService.reduceCouponNum(params);
            return RespBean.success("领取成功");
        } else {
            return RespBean.error("领取失败");
        }
    }

    /**
     * 获取用户中心的优惠券分页数据
     *
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean gerUserCenterCouponPage(PageVO vo, UserCentCouponSearchParam param) {
        IPage<MemberCouponEntity> page = this.baseMapper.gerUserCenterCouponPage(PageUtil.initPage(vo), param, new Date());

        return RespBean.success("获取成功", page);
    }

    /**
     * 获取用户领取的优惠券中 全部的 可以使用后的优惠券
     *
     * @param params
     * @return
     */
    @Override
    public RespBean getUserAllCanUseCoupon(Map<String, Object> params) {
        Long userId = MapUtil.getLong(params, "userId");
        Long skuId = MapUtil.getLong(params, "skuId");
        Long cateId = MapUtil.getLong(params, "cateId");

        // 查询出没过期 而且属于当前用户领取的全部优惠券 而且并未使用过
        List<MemberCouponEntity> memberCouponEntityList = this.list(new QueryWrapper<MemberCouponEntity>()
                .lt("start_time", new Date())
                .gt("end_time", new Date())
                .ne("member_coupon_status", MemberCouponStatusEnum.USED)
                .eq("member_id", userId));

        List<MemberCouponEntity> list = new ArrayList<>();
        for (MemberCouponEntity entity : memberCouponEntityList) {
            // 过滤出可用的
            if (entity.getScopeType().equals("ALL")){
                list.add(entity);
            }
            if (entity.getScopeType().equals("PORTION_GOODS")){
                // 如果是指定了商品 那就要对比使用范围和传入的ID
                List<String> collect = Arrays.stream(entity.getScopeId().split(",")).collect(Collectors.toList());
                for (String s : collect) {
                    if (skuId.equals(Long.parseLong(s))){
                        list.add(entity);
                    }
                }
            }
            if (entity.getScopeType().equals("PORTION_GOODS_CATEGORY")){
                // 如果是指定了分类那就要对比传入的分类和scopeid的分类id是否对的上
                List<String> cateIDS = Arrays.stream(entity.getScopeId().split(",")).collect(Collectors.toList());
                for (String cateID : cateIDS) {
                    if (cateId.equals(Long.parseLong(cateID))){
                        list.add(entity);
                    }
                }
            }
        }

        return RespBean.success("获取成功",list);

    }

    /**
     * 根据传入的购物车项获取当前用户结算时可用的优惠券
     *
     * @param list
     * @return
     */
    @Override
    public List<MemberCouponEntity> getUserAllCanUseCouponByCART(List<MemberCartEntity> list) {
        // 查询出没过期 而且属于当前用户领取的全部优惠券 而且并未使用过
        List<MemberCouponEntity> memberCouponEntityList = this.list(new QueryWrapper<MemberCouponEntity>()
                .lt("start_time", new Date())
                .gt("end_time", new Date())
                .ne("member_coupon_status", MemberCouponStatusEnum.USED)
                .eq("member_id", list.get(0).getMemberId()));
        List<Long> skuIds = list.stream().map(MemberCartEntity::getSkuId).distinct().collect(Collectors.toList());
        List<Long> cateIds = list.stream().map(MemberCartEntity::getCatalogId).collect(Collectors.toList());
        List<MemberCouponEntity> memberCouponEntities = new ArrayList<>();
        for (MemberCouponEntity entity : memberCouponEntityList) {
            // 过滤出可用的
            if (entity.getScopeType().equals("ALL")){
                memberCouponEntities.add(entity);
            }
            if (entity.getScopeType().equals("PORTION_GOODS")){
                // 如果是指定了商品 那就要对比使用范围和传入的ID
                List<String> collect = Arrays.stream(entity.getScopeId().split(",")).collect(Collectors.toList());
                for (String s : collect) {
                    for (Long skuId : skuIds) {
                        if (skuId.equals(Long.parseLong(s))){
                            memberCouponEntities.add(entity);
                        }
                    }
                }
            }
            if (entity.getScopeType().equals("PORTION_GOODS_CATEGORY")){
                List<String> collect = Arrays.stream(entity.getScopeId().split(",")).collect(Collectors.toList());
                for (String s : collect) {
                    for (Long cateId : cateIds) {
                        if (cateId.equals(Long.parseLong(s))){
                            memberCouponEntities.add(entity);
                        }
                    }
                }
            }
        }
        List<MemberCouponEntity> collect = memberCouponEntities.stream().distinct().collect(Collectors.toList());
        return collect;
    }


































}